<?php

class cart{
	
	function __construct(){
		session_start();
	}

	function cart_list(){
		return $_SESSION['cart'];
	}

	function cart_add($goods_id=0, $num=1)
	{
		global $db;
		$goods = $db->get_row("SELECT * FROM ".t('goods')." WHERE id='$goods_id'");
		if(empty($goods)) return false;
		$cart = array('goods_id'=>(int)$goods_id, 'num'=>(int)$num, 'price'=>(float)$goods['price']);
		//判断商品库存(todo)...

		//已存在
		if(count($_SESSION['cart']['goods']) > 0){
			foreach($_SESSION['cart']['goods'] as $k=>$v){
				//$_SESSION['cart']['goods'][$k];
				if($v['goods_id'] == $goods_id){	
					$_SESSION['cart']['goods'][$k]['num'] = $_SESSION['cart']['goods'][$k]['num']+$num;
					$_SESSION['cart']['amount'] = $_SESSION['cart']['amount']+$goods['price']*$num;
					return $_SESSION['cart'];
				}
			}
		}
		//不存在
		$_SESSION['cart']['goods'][] = $cart;
		$_SESSION['cart']['amount']  = $_SESSION['cart']['amount']+$goods['price']*$num;
		return $_SESSION['cart'];
	}

	function cart_del($goods_id=0){
		if(count($_SESSION['cart']['goods']) > 0){
			foreach($_SESSION['cart']['goods'] as $k=>$v){
				$_SESSION['cart']['goods'][$k];
				if($v['goods_id'] == (int)$goods_id){
					$_SESSION['cart']['amount'] = $_SESSION['cart']['amount']-$_SESSION['cart']['goods'][$k]['price']*$_SESSION['cart']['goods'][$k]['num'];
					unset($_SESSION['cart']['goods'][$k]);
				}
			}	
		}
		return $_SESSION['cart'];
	}

	function cart_empty(){
		$_SESSION['cart'] = array();
		$_SESSION['cart']['goods'] = array();
		$_SESSION['cart']['amount'] = 0;
		return $_SESSION['cart'];
	}

	//生成订单
	function order_save($desk_id=0,$user_id=0,$paytype=1,$payuser_num=1){
		global $db;
		$cart = $this->cart_list();
		if(count($cart) <= 0) return false;
		//库存加减(todo)...

		//保存订单
		$order = array('order_sn'=>order_sn(),
			'desk_id'=>$desk_id,
			'user_id'=>$user_id,
			'cart'=>serialize($cart),
			'paytype'=>(int)$paytype,
			'payuser_num'=>(int)$payuser_num,
			'addtime'=>time()
		);
		$db->query( $db->insert_sql(t('order'), $order) );
		//生成未支付记录
		$paylog = array(
			'order_id'=>$db->insert_id(),
			'user_id'=>$user_id,
			'amount'=> sprintf("%.2f",($_SESSION['cart']['amount']/$payuser_num) ), 
		);
		for ($i=0; $i < $payuser_num; $i++) { 
			$db->query( $db->insert_sql(t('order_pay'), $paylog) );
		}
		$this->cart_empty();
		return true;
	}

	function order_pay($user_id,$order_id){
		$paylog = array(
			'user_id'=>$user_id,
		);
		$db->query( $db->update_sql(t('order_pay'), $paylog, "order_id='$order_id' AND paystate='".PAYSTATE_NO."'") );
		$nopay_count = $db->get_one("SELECT count(*) count FROM ".t('order_pay')." WHERE order_id='$order_id' AND paystate='".PAYSTATE_NO."'");
		//已经全部支付完成,更新总订单状态
		if($nopay_count == 0){
			$db->query( $db->update_sql(t('order'), array('paystate'=>PAYSTATE_YES), "id='$order_id'") );
			return true;
		}
		return $nopay_count;
	}

}
